<template>
  <el-dialog title="章节信息" :visible="true">
    <el-form>
      <el-form-item label="课程名称">
        <el-input v-model="courseName" :disabled="true"></el-input>
      </el-form-item>
      <el-form-item label="章节名称">
        <el-input v-model="section.sectionName"></el-input>
      </el-form-item>
      <el-form-item label="章节描述">
        <el-input v-model="section.description"></el-input>
      </el-form-item>
      <el-form-item label="章节排序">
        <el-input
          type="number"
          :min="0"
          v-model="section.orderNum"
        >
          <template slot="append">数字控制排序，数字越大越靠后</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('close')">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getSectionById, saveOrUpdateSection } from '@/services/section'

  export default {
    name: 'CreateOrEditSection',
    props: {
      courseId: {
        type: [Number, String],
        required: true,
      },
      courseName: {
        type: String,
        required: true,
      },
      sectionId: {
        type: [Number, String],
      },
    },
    data() {
      return {
        section: {
          sectionName: '',
          description: '',
          orderNum: '',
        },
      }
    },
    created() {
      if (this.sectionId) {
        this.loadSectionData()
      }
    },
    methods: {
      async loadSectionData() {
        const { code, data } = await getSectionById(this.sectionId)
        if (code === '000000') {
          this.section = data
        }
      },
      async onSubmit() {
        const data = Object.assign(this.section, { courseId: this.courseId, courseName: this.courseName })
        const { code } = await saveOrUpdateSection(data)
        if (code === '000000') {
          this.$message.success(`${this.sectionId ? '修改' : '添加'}成功！`)
          this.$emit('success')
        }
      },
    },
  }
</script>
